{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# <center>第10章 网络编程与并发处理</center>\n",
    "\n",
    "<br>\n",
    "\n",
    "- [10.1 网络套接字的概念](：#10.1-网络套接字的概念)\n",
    "  - [10.1.1 套接字的类型](：#10.1.1-套接字的类型)\n",
    "  - [10.1.2 基于套接字的网络通信过程](：#10.1.2-基于套接字的网络通信过程)\n",
    "- [10.2 套接字编程](：#10.2-套接字编程)\n",
    "  - [10.2.1 socket模块](：#10.2.1-socket模块)\n",
    "  - [10.2.2 面向连接的套接字编程](：#10.2.2-面向连接的套接字编程)\n",
    "  - [10.2.3 面向无连接套接字编程](：#10.2.3-面向无连接套接字编程)\n",
    "  - [10.2.4 并发问题](：#10.2.4-并发问题)\n",
    "- [10.3 多进程编程](：#10.3-多进程编程)\n",
    "  - [10.3.1 进程的创建与运行](：#10.3.1-进程的创建与运行)\n",
    "  - [10.3.2 利用多进程处理网络并发](：#10.3.2-利用多进程处理网络并发)\n",
    "  - [10.3.3 利用进程池处理网络并发](：#10.3.3-利用进程池处理网络并发)\n",
    "- [10.4 多线程编程](：#10.4-多线程编程)\n",
    "  - [10.4.1 线程的概念与特点](：#10.4.1-线程的概念与特点)\n",
    "  - [10.4.2 网络并发处理的多线程方法](：#10.4.2-网络并发处理的多线程方法)\n",
    "- [10.5 异步编程 *](：#10.5-异步编程-*)\n",
    "  - [10.5.1 异步编程概念](：#10.5.1-异步编程概念)\n",
    "  - [10.5.2 基于生成器的协程](：#10.5.2-基于生成器的协程)\n",
    "  - [10.5.3 协程](：#10.5.3-协程)\n",
    "  - [10.5.4 Python 异步编程基础](：#10.5.4-Python-异步编程基础)\n",
    "  - [10.5.5 利用异步编程处理网络并发](：#10.5.5-利用异步编程处理网络并发)\n",
    "- [10.6 套接字服务器](：#10.6-套接字服务器)\n",
    "  - [10.6.1 `socketserver`模块简介](：#10.6.1-socketserver模块简介)\n",
    "  - [10.6.2 利用套接字服务器处理网络并发](：#10.6.2-利用套接字服务器处理网络并发)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## 10.1 网络套接字的概念\n",
    "\n",
    "- 套接字（Socket）\n",
    "  - 是一种用于网络通信的数据结构，是对 TCP 协议或 UDP 协议的封装，用于 描述计算机网络上的一个通信终端\n",
    "  - 客户机端套接字和服务器端套接字\n",
    "- 套接字源于伯克利版本的 Unix 系统(即 BSD Unix)\n",
    "  - 最初被用于作为进程间通信 (Inter Process Communication, IPC)的一种方式\n",
    "  - 也称为伯克利套接字或 BSD 套接字"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 10.1.1 套接字的类型\n",
    "\n",
    "- 基于文件的套接字\n",
    "  - 用于在同一计算机的不同进程之间通信时基于文件实现\n",
    "  - 地址簇(Address Family)名称`AF_UNIX`\n",
    "- 基于网络的套接字\n",
    "  - 用于不同计算机之间通 信\n",
    "  - 地址簇名称为`AF_INET`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 面向连接的套接字\n",
    "  - 基于 TCP 协 议实现\n",
    "  - `SOCK_STREAM`\n",
    "- 面向无连接的套接字\n",
    "  - 基于 UDP 协议实现\n",
    "  - `SOCK_DGRAM`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 10.1.2 基于套接字的网络通信过程\n",
    "\n",
    "- 面向连接的套接字（TCP）\n",
    "\n",
    "<center>\n",
    "    <img src=\"./figures/fig10-1.png\" width=\"60%\"/>\n",
    "</center>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 面向无连接的套接字（UDP）\n",
    "\n",
    "<center>\n",
    "    <img src=\"./figures/fig10-2.png\" width=\"60%\"/>\n",
    "</center>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "## 10.2 套接字编程\n",
    "\n",
    "### 10.2.1 socket模块\n",
    "\n",
    "- `socket`函数\n",
    "  - 用于创建一个套接字对象\n",
    "  - 参数\n",
    "    - `family`:地址簇，取值可为`AF_INET`(默认)、`AF_INET6`、`AF_UNIX`、`AF_CAN`, `AF_PACKET` 或`AF_RDS`\n",
    "    - `type`:套接字类型，取值可为`SOCK_STREAM`(默认)、`SOCK_DGRAM`、`SOCK_RAW`或者 其他名称以`SOCK_`开头的常量之一\n",
    "    - `proto`:协议号，通常取值为 0，当协议簇为`AF_CAN`时取值为`CAN_RAW`、`CAN_BCM`、 `CAN_ISOTP`或`CAN_J1939`之一;\n",
    "    - `fileno`:套接字文件描述符，如果指定了`fileno`，那么将从中自动检测`family`、`type` 和`proto`的值，更重要的是在不同程序中使用相同的套接字文件描述符能够获取同 一个套接字对象"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 套接字对象常用方法和属性\n",
    "\n",
    "| 方法/属性                     | 功能                                                         |\n",
    "| :--------------------------- | :---------------------------------------------------------- |\n",
    "| `bind(address) `              | 用于服务器端，将套接字绑定到地址 `address`，`address` 是由 IP 字符串和端口号组成的元组。 |\n",
    "| `listen(backlog)`             | 用于服务器端，启动监听准备接受连接请求。`backlog` 用于指 定等待建立连接的最大客户端请求数量，未指定时根据系统状  态自动设定合理取值。 |\n",
    "| `accept()`                    | 用于服务器端，接受一个连接请求，返回一个用于向客户端发 送数据的套接字对象以及客户端地址。 |\n",
    "| `connect(address)`            | 用于客户端，向服务器端发起连接请求，当使用 `AF_INET` 地 址簇时，`address` 是服务器端 IP 字符串和端口号组成的元组。 |\n",
    "| `recv(bufsize)`               | 从 TCP 套接字接中收数据，返回值一个字节串，`bufsize` 用 于指定一次接收的最大数据量。 |\n",
    "| `recv_into(buffer, nbytes)`   | 从 TCP 套接字接收至多 `nbytes` 个字节，将其写入缓冲区而 不是创建新的字节串，`nbytes` 默认为 0，表示接受的最大数据  量取决于缓冲区大小。 |\n",
    "| `send(bytes)`                 | 通过 TCP 套接字发送数据，`bytes` 为字节串。                  |\n",
    "| `sendall(bytes)`              | 持续发送 TCP 数据 `bytes`，直到发送完毕或发生错误，成功 返回 `None`。 |\n",
    "| `recv_from(bufsize)`          | 从 UDP 套接字接中收数据，返回值字节串和发送端地址， `bufsize` 用于指定一次接收的最大数据量。 |\n",
    "| `recv_from_into`              | 从 UDP 套接字接收至多 `nbytes` 个字节，将其写入缓冲区而 不是创建新的字节串，`nbytes` 默认为 0，表示接受的最大数据  量取决于缓冲区大小，返回值字节串和发送端地址。 |\n",
    "| `sendto(bytes, address)`      | 通过 UDP 套接字发送数据 `bytes` 至 `address`。               |\n",
    "| `getpeername()`               | 返回 TCP 套接字连接到的远程地址。                            |\n",
    "| `getsockname()`               | 返回当前套接字的地址。                                       |\n",
    "| `shutdown(how)`               | 半关闭或全关闭 TCP 连接，`how` 取值为 `SHUT_RD`、`SHUT_WR` 或  `SHUT_RDWR`，表示关闭后不再允许接收、发送或者都不允许。 |\n",
    "| `close()`                     | 关闭套接字。                                                 |\n",
    "| `setsockopt(level,opt,value)` | 设置套接字选项取值。                                         |\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 10.2.2 面向连接的套接字编程\n",
    "\n",
    "- TCP 服务器端（eg_10-01）\n",
    "\n",
    "```python\n",
    "from socket import socket, AF_INET, SOCK_STREAM\n",
    "from socket import SOL_SOCKET, SO_REUSEADDR\n",
    "from datetime import datetime\n",
    "\n",
    "server_socket = socket(AF_INET, SOCK_STREAM)          # 创建套接字对象\n",
    "server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # 端口重用\n",
    "server_socket.bind(('127.0.0.1', 9000))               # 绑定地址\n",
    "server_socket.listen()                                # 监听\n",
    "print('TCP服务器启动，监听之中... ...')\n",
    "\n",
    "while True:                                           # 服务循环\n",
    "    conn, client_addr = server_socket.accept()        # 接受连接请求\n",
    "    print(f'客户端{client_addr}连接成功，等待输入 ...')\n",
    "\n",
    "    while True:                                       # 通信循环\n",
    "        data_recv = conn.recv(1024).decode('utf-8')   # 接收数据\n",
    "\n",
    "        now = datetime.now().strftime(\"%H:%M:%S\")\n",
    "        print(f'{now} 接收到数据：{data_recv}')\n",
    "        send_data = f'接收到长度为 {len(data_recv)} 的数据'\n",
    "        conn.send(send_data.encode('utf-8'))          # 发送数据\n",
    "\n",
    "        if not data_recv:\n",
    "            conn.close()                              # 关闭连接\n",
    "            break\n",
    "    print(f'客户端{client_addr}连接结束！')\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- TCP 客户端（eg_10-02）\n",
    "\n",
    "```python\n",
    "from socket import socket, AF_INET, SOCK_STREAM\n",
    "from datetime import datetime\n",
    "\n",
    "tcp_socket = socket(AF_INET, SOCK_STREAM)    # 创建套接字\n",
    "tcp_socket.connect(('127.0.0.1', 9000))               # 发起连接请求\n",
    "while True:\n",
    "    data_send = input('> ')\n",
    "    tcp_socket.send(data_send.encode('utf-8'))        # 发送数据\n",
    "    if not data_send:\n",
    "        break\n",
    "    data_recv = tcp_socket.recv(1024)                 # 接收数据\n",
    "    now = datetime.now().strftime(\"%H:%M:%S\")\n",
    "    print(f'{now} 服务器回复：{data_recv.decode(\"utf-8\")}')\n",
    "tcp_socket.close()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- __注意：需要将上述服务器端和客户端保存为脚本，在两个终端分别运行。__\n",
    "\n",
    "<center>\n",
    "    <img src=\"./figures/fig10-3.png\" width=\"80%\"/>\n",
    "</center>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 10.2.3 面向无连接套接字编程\n",
    "\n",
    "- UDP 服务器端（eg_10-03）\n",
    "\n",
    "```python\n",
    "from socket import socket, AF_INET, SOCK_DGRAM\n",
    "from socket import SOL_SOCKET, SO_REUSEADDR\n",
    "from datetime import datetime\n",
    "\n",
    "server_socket = socket(AF_INET, SOCK_DGRAM)              # 创建套接字\n",
    "server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)    # 端口重用\n",
    "server_socket.bind(('127.0.0.1', 9000))                  # 绑定地址\n",
    "print('UDP服务器启动，等待客户端数据 ...')\n",
    "\n",
    "while True:\n",
    "    data_recv, address = server_socket.recvfrom(1024)    # 接收数据\n",
    "    now = datetime.now().strftime(\"%H:%M:%S\")\n",
    "    data_recv = data_recv.decode(\"utf-8\")\n",
    "    print(f'{now}接收到来自{address[0]}的数据：{data_recv}')\n",
    "    data_send = f'接收到长度为 {len(data_recv)} 的数据'.encode('utf-8')\n",
    "    server_socket.sendto(data_send, address)             # 发送数据\n",
    "server_socket.close()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- UDP客户端（eg_10-04）\n",
    "\n",
    "```python\n",
    "from socket import socket, AF_INET, SOCK_DGRAM\n",
    "import datetime\n",
    "\n",
    "client_socket = socket(AF_INET, SOCK_DGRAM)            # 创建套接字\n",
    "while True:\n",
    "    data_send = input('> ').encode(\"utf-8\")\n",
    "    if not data_send:\n",
    "        break\n",
    "    client_socket.sendto(data_send, ('127.0.0.1', 9000))  # 发送数据\n",
    "    data_recv, addr = client_socket.recvfrom(1024)        # 接收数据\n",
    "    now = datetime.datetime.now().strftime(\"%H:%M:%S\")\n",
    "    data_recv = data_recv.decode(encoding=\"utf-8\")\n",
    "    print(f'{now} 服务器回复：{data_recv}')\n",
    "client_socket.close()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 在终端中运行\n",
    "\n",
    "<center>\n",
    "    <img src=\"./figures/fig10-4.png\" width=\"80%\"/>\n",
    "</center>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 10.2.4 并发问题\n",
    "\n",
    "- 并发\n",
    "  - 在一个很短的时间段内多个客户端同时对服务器发起连接请求\n",
    "  - 对于基于面向连接的应用来说，并发带来的问题尤其严重\n",
    "- 并发处理\n",
    "  - 多进程编程\n",
    "  - 多线程编程\n",
    "  - 异步编程\n",
    "  - 多路复用"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## 10.3 多进程编程\n",
    "\n",
    "### 10.3.1 进程的创建与运行\n",
    "\n",
    "- 多进程编程相关的模块\n",
    "  - `multiprocessing`\n",
    "  - `subprocess`\n",
    "- `multiprocessing.Process`类\n",
    "  - 实现多进程编程\n",
    "  - 初始化参数\n",
    "    - `group`: 取值总是为`None`，其存在只是为了与多线程编程的 API 相兼容; \n",
    "    - `target`: 进程的调用目标，是一个可调用对象，表示该进程要执行的任务; \n",
    "    - `name`: 进程的名称;\n",
    "    - `args`: 传递给调用目标的位置参数元组;\n",
    "    - `kwargs`: 传递给调用目标的关键字参数字典;\n",
    "    - `daemon`: 新的进程是否守护进程，取值为`True`或`False`。守护进程是一直在后台运行不受终端控制的特殊子进程，主要用于为其他子进程提供服务。父进程在退出时会终止所有守护子进程。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `Process` 类的常用方法和属性\n",
    "\n",
    "|方法/属性| 作用|\n",
    "|:--|:--|\n",
    "|`run()`| 进程所执行的方法，该方法会调用 `target` 属性或者在子类中被重写 |\n",
    "|`start()`| 启动进程|\n",
    "|`join(timeout)`| 由父进程调用以阻塞自己直到子进程结束，`timeout` 默认取值为 `None` |\n",
    "|`is_alive()`|  进程是否仍处理活动状态|\n",
    "|`terminate()`| 终止进程|\n",
    "|`daemon`| 是否是守护进程，如果要设置该属性的值，必须在 `start` 方法调用之前 |\n",
    "|`pid`|  进程号|\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- `Process`类的使用方法有两种\n",
    "  - 创建`Process`类对象时指定`target`参数\n",
    "  - 继承`Process`类"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 通过指定`target`创建子进程（eg_10-05）\n",
    "\n",
    "```python\n",
    "import os\n",
    "import time\n",
    "from multiprocessing import Process\n",
    "\n",
    "def target_fun(name_):\n",
    "    print(f'这里是子进程{name_}')\n",
    "    time.sleep(20)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    subp_A = Process(target=target_fun, args='A')\n",
    "    subp_B = Process(target=target_fun, args='B')\n",
    "    subp_A.start()\n",
    "    subp_B.start()\n",
    "    print(f'这里是父进程，进程ID为 {os.getpid()}')\n",
    "    print(f'子进程A的ID为 {subp_A.pid}')\n",
    "    print(f'子进程B的ID为 {subp_B.pid}')\n",
    "    subp_A.join()\n",
    "    subp_B.join()\n",
    "```\n",
    "\n",
    "- 运行结果\n",
    "```bash\n",
    "这里是父进程，进程ID为 2042\n",
    "子进程A的ID为 2043\n",
    "子进程B的ID为 2044\n",
    "这里是子进程B\n",
    "这里是子进程A\n",
    "```\n",
    "\n",
    "- 进程树\n",
    "\n",
    "<center>\n",
    "    <img src=\"./figures/fig10-5.png\" width=\"30%\"/>\n",
    "</center>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 通过继承`Process`类创建子进程（eg_10-06）\n",
    "\n",
    "```python\n",
    "import os\n",
    "import time\n",
    "from multiprocessing import Process\n",
    "\n",
    "class SubProcess(Process):\n",
    "    def __init__(self, name_):\n",
    "        self.__name = name_\n",
    "        super().__init__()\n",
    "\n",
    "    def run(self):\n",
    "        print(f'这里是子进程{self.__name}')\n",
    "        time.sleep(20)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    subp_A = SubProcess('A')\n",
    "    subp_B = SubProcess('B')\n",
    "    subp_A.start()\n",
    "    subp_B.start()\n",
    "    print(f'这里是父进程，进程ID为 {os.getpid()}')\n",
    "    print(f'子进程A的ID为 {subp_A.pid}')\n",
    "    print(f'子进程B的ID为 {subp_B.pid}')\n",
    "    subp_A.join()\n",
    "    subp_B.join()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 10.3.2 利用多进程处理网络并发\n",
    "\n",
    "- 每当服务器端接受一个客户端发起的连接请求时，就新建一个进程来为客户端提供服务\n",
    "  - eg_10-07\n",
    "  - TCP client: eg_10-02\n",
    "\n",
    "```python\n",
    "from socket import socket, AF_INET, SOCK_STREAM\n",
    "from socket import SOL_SOCKET, SO_REUSEADDR\n",
    "from datetime import datetime\n",
    "from multiprocessing import Process\n",
    "\n",
    "\n",
    "class ServiceProcess(Process):\n",
    "    def __init__(self, socket, addr):\n",
    "        self.conn = socket\n",
    "        self.addr = addr\n",
    "        super().__init__()\n",
    "\n",
    "    def run(self):\n",
    "        print(f'客户端{self.addr}连接成功，等待输入 ...')\n",
    "        while True:                                       # 通信循环\n",
    "            data_recv = self.conn.recv(1024)              # 接收数据\n",
    "            data_recv = data_recv.decode('utf-8')\n",
    "            now = datetime.now().strftime(\"%H:%M:%S\")\n",
    "            print(f'{now} 接收到来自{self.addr}的数据：{data_recv}')\n",
    "            send_data = f'接收到长度为 {len(data_recv)} 的数据'\n",
    "            self.conn.send(send_data.encode('utf-8'))     # 发送数据\n",
    "            if not data_recv:\n",
    "                self.conn.close()\n",
    "                break\n",
    "        print(f'客户端{self.addr}连接结束！')\n",
    "\n",
    "\n",
    "def main():\n",
    "    server_socket = socket(AF_INET, SOCK_STREAM)        # 创建套接字对象\n",
    "    server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)  # 端口重用\n",
    "    server_socket.bind(('127.0.0.1', 9000))               # 绑定地址\n",
    "    server_socket.listen()                                # 监听\n",
    "    print('TCP服务器启动，监听之中... ...')\n",
    "    while True:\n",
    "        conn_socket, addr = server_socket.accept()        # 接受连接请求\n",
    "        subp = ServiceProcess(conn_socket, addr)          # 创建子进程\n",
    "        subp.start()                                      # 启动子进程\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 10.3.3 利用进程池处理网络并发\n",
    "\n",
    "- 进程池\n",
    "  - 进程池是一种维护进程的数据类型\n",
    "    - 它在启动的时候创建一定量的空闲进程，每当需要的时候就取出一个进程来执行任务\n",
    "    - 任务结束之后进程并不会退出，而是放回进程池中重新进入空闲状态等待下次调用\n",
    "  - 避免频繁创建和销毁进程带来的开销，能够大大降低系统的压力\n",
    "- 进程池的实现\n",
    "  - Python中进程池由`multiprocessing`的`pool`子模块中的`Pool`类实现\n",
    "  - 为了与线程池的API相统一，`concurrent.futures`中的`ProcessPoolExecutor`类对`Pool`进行了包装"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 利用进程池实现并发处理（eg_10-08）\n",
    "  - TCP client: eg_10-02\n",
    "\n",
    "```python\n",
    "from socket import socket, AF_INET, SOCK_STREAM\n",
    "from socket import SOL_SOCKET, SO_REUSEADDR\n",
    "from datetime import datetime\n",
    "from concurrent.futures import ProcessPoolExecutor\n",
    "\n",
    "\n",
    "def service_task(conn, addr):\n",
    "    print(f'客户端{addr}连接成功，等待输入 ...')\n",
    "    while True:                                           # 通信循环\n",
    "        data_recv = conn.recv(1024).decode('utf-8')       # 接收数据\n",
    "        now = datetime.now().strftime(\"%H:%M:%S\")\n",
    "        print(f'{now} 接收到来自{addr}的数据：{data_recv}')\n",
    "        send_data = f'接收到长度为 {len(data_recv)} 的数据'\n",
    "        conn.send(send_data.encode('utf-8'))              # 发送数据\n",
    "        if not data_recv:\n",
    "            conn.close()\n",
    "            break\n",
    "    print(f'客户端{addr}连接结束！')\n",
    "\n",
    "\n",
    "def main():\n",
    "    server_socket = socket(AF_INET, SOCK_STREAM)        # 创建套接字对象\n",
    "    server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)  # 端口重用\n",
    "    server_socket.bind(('127.0.0.1', 9000))               # 绑定地址\n",
    "    server_socket.listen()\n",
    "    print('TCP服务器启动，监听之中... ...')\n",
    "    pool = ProcessPoolExecutor(10)                        # 进程池\n",
    "    while True:\n",
    "        conn, addr = server_socket.accept()               # 接受连接请求\n",
    "        pool.submit(service_task, conn, addr)\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "## 10.4 多线程编程\n",
    "\n",
    "\n",
    "### 10.4.1 线程的概念与特点\n",
    "\n",
    "- 线程\n",
    "  - 又称为轻量级进程，运行开销远小于进程，是并发编程的一种有效方法\n",
    "  - 线程是为了进一步提高程序并发处理能力而在进程中引入的一种执行单元\n",
    "- 多线程编程\n",
    "  - 当进程中的线程数量多于一个时，就称为多线程编程\n",
    "- 线程的优势\n",
    "  - 消耗的 CPU 和内存资源更少，隶属于同一进程的线程共享着进程的绝大多数资源\n",
    "  - 线程的切换开销也远小于进程切换\n",
    "  - 能够利用多个或多核 CPU（Python中由于全局锁的存在而不具备这样的能力）\n",
    "- 实现\n",
    "  - `threading`模块\n",
    "  - `Thread`类\n",
    "  - Python 统一了多线程编程和多进程编程的 API，因此`Thread`类和`Process`类使用方法基本相同"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 10.4.2 网络并发处理的多线程方法\n",
    "\n",
    "- 多线程\n",
    "  - 将多进程并发处理中的`Process`类直接替换为`Thread`类即可\n",
    "- 线程池\n",
    "  - 将进程池并发正理中的`ProcessPoolExecutor`类直接替换为`ThreadPoolExecutor`类即可"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## 10.5 异步编程 *\n",
    "\n",
    "- 异步编程是一种新型的并发处理技术，能够在单线程中以极高的效率处理输入/输出 密集型并发任务\n",
    "\n",
    "### 10.5.1 异步编程概念\n",
    "\n",
    "- 计算机程序的类型\n",
    "  - 计算密集型\n",
    "  - 输入/输出密集型\n",
    "    - 网络程序就是一种典型的输入/输出密集型任务，套接字对象的`accept`、 `send`、`recv`等方法都会导致服务器端程序阻塞\n",
    "- 同步运行\n",
    "  - 程序要执行的多项操作按时间顺序进行\n",
    "    - 当遇到输入/输出时即阻塞等待，直到输入/输出结束后继续执行\n",
    "- 异步运行\n",
    "  - 程序在运行过程中遇到输入/输出时不发生阻塞，而是跳转到能够继续执行的其他位置继续运行\n",
    "  - 等输入/输出结束之后，在合适的时机会跳转回来继续执行"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 程序的同步运行与异步运行\n",
    "\n",
    "<br>\n",
    "<center>\n",
    "    <img src=\"./figures/fig10-6.png\" width=\"80%\"/>\n",
    "</center>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 异步编程的优势\n",
    "  - 仅利用一个进程或线程就能够实现输入/输出密集型任务的并发处理\n",
    "  - 业务之间发生切换时，没有导致进程或线程的切换，节省了大量的计算机资源开销，从而能够以极高的效率处理并发问题\n",
    "  - 程序运行于同一线程或进程之中，不需要使用复杂的锁来实现同步"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 10.5.2 基于生成器的协程\n",
    "\n",
    "- 生成器的一个重要的特征是惰性计算，`yield` 语句返回一个值之后函数的运行被暂停，这就为程序的异步运行提供了可能性\n",
    "\n",
    "- 与普通生成器相比，生成器协程的特点有\n",
    "  - `yield` 能够在表达式中使用，即可用于发送数据也能用于接收数据\n",
    "  - 主调函数可以利用`send`方法向生成器发送数据\n",
    "  - 可使用`close`方法和`throw`方法终止生成器或向生成器抛出异常"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 利用`yield`语句接收数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def test_coroutine():\n",
    "    while True:\n",
    "        x = yield\n",
    "        print(f\"传入的值为{x}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "tc1 = test_coroutine()\n",
    "tc2 = test_coroutine()\n",
    "next(tc1)    # 预激活协程tc1\n",
    "next(tc2)    # 预激活协程tc2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "传入的值为0\n"
     ]
    }
   ],
   "source": [
    "tc1.send(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "传入的值为1\n"
     ]
    }
   ],
   "source": [
    "tc2.send(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "tc1.close()\n",
    "tc2.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 利用 `yield` 同时接收并返回数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def cumulative_average():\n",
    "    n = 0\n",
    "    total = 0\n",
    "    avg = 0\n",
    "    while True:\n",
    "        x = yield avg\n",
    "        total += x\n",
    "        n += 1\n",
    "        avg = total/n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "ca = cumulative_average()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "next(ca)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.0"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ca.send(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10.0"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ca.send(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10.0"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ca.send(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "ca.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 生成器协程的状态\n",
    "  - `GEN_CREATED`: 生成器刚刚创建出来，等待激活执行\n",
    "  - `GEN_RUNNING`: 生成器正在执行中\n",
    "  - `GEN_SUSPENDED`: 生成器执行至 `yield` 语句处暂停\n",
    "  - `GEN_CLOSED`: 生成器被终止。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'GEN_CREATED'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from inspect import getgeneratorstate \n",
    "tc = test_coroutine()\n",
    "getgeneratorstate(tc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'GEN_SUSPENDED'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "next(tc)\n",
    "getgeneratorstate(tc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'GEN_CLOSED'"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tc.close()\n",
    "getgeneratorstate(tc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 10.5.3 协程\n",
    "\n",
    "- 生成器协程的使用比较复杂，并且其功能超出了生成器的范畴\n",
    "- Python 3.4 加入了`asyncio`模块，定义了`corountine`装饰器用于将函数变为协程，才终于使协程与生成器相分离，成为不同的数据类型\n",
    "- Python 3.5 中引入了`async`和`await`两个关键字，替代`corountine`装饰器和`yield from`关键字，简化了异步编程"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 协程函数\n",
    "  - 使用`async`关键字定义的函数称为协程函数\n",
    "  - 调用协程函数返回一个协程对象\n",
    "- `await`\n",
    "  - 用于使协程交出运行的控制权，只能在协程函数内部使用\n",
    "  - 在交出控制权的同时等待输入/输出操作结束，并获取返回结果\n",
    "- 链式协程\n",
    "  - 在一个协程中用await语句调用其他的 协程就形成了链式协程"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 协程的定义和运行(eg_10-12)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "import asyncio\n",
    "\n",
    "async def coroutine(name):\n",
    "    print(f'协程 {name} 开始运行...')\n",
    "    await asyncio.sleep(1)                  # 模拟输入/输出  \n",
    "    print(f'协程 {name} 运行结束！')\n",
    "    return f'协程{name}运行结果'\n",
    "\n",
    "async def main():\n",
    "    c_A = coroutine('A')                    # 协程A\n",
    "    c_B = coroutine('B')                    # 协程B\n",
    "    c_C = coroutine('C')                    # 协程C\n",
    "    r = await asyncio.gather(c_A, c_B, c_C) # 创建并发任务\n",
    "    return r\n",
    "\n",
    "r = asyncio.run(main())\n",
    "print(r)\n",
    "```\n",
    "输出结果：\n",
    "```bash\n",
    "协程 A 开始运行...\n",
    "协程 B 开始运行...\n",
    "协程 C 开始运行...\n",
    "协程 A 运行结束！\n",
    "协程 B 运行结束！\n",
    "协程 C 运行结束！\n",
    "['协程A运行结果', '协程B运行结果', '协程C运行结果']\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 10.5.4 Python 异步编程基础\n",
    "\n",
    "- 异步编程的关键概念和数据类型\n",
    "  - 事件循环\n",
    "    - 是异步程序运行的核心，负责不断收集各种异步编程事件（输入/输出开始和完成），并在一个事件发生之后分配执行权限\n",
    "    - 使用`asyncio.get_event_loop`获取当前的事件循环对象\n",
    "  - `Future`\n",
    "    - 表示未完成的异步任务对象\n",
    "    - 待执行或中断执行的协程对象会被包装成为`Future`对象\n",
    "    - 事件循环通过Future对象来实现对协程异步调度\n",
    "    - Future对象也可 以用于获取异步任务的执行结果\n",
    "  - `Task`\n",
    "    - `Future`的子类，协程对象通常会被包装为`Task`然后放入事件循环\n",
    "    - 使用`asyncio.create_task`函数创建`Task`对象"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 异步编程的步骤\n",
    "  - 定义协程函数\n",
    "    - 使用`async`和`await`关键字\n",
    "  - 创建协程对象并包装为并发任务\n",
    "    - 使用`loop.create_task`方法用协程对象创建任务(`Task`)并在事件循环中注册\n",
    "    - 或者利用`asyncio.gether`函数将多个协程对象包装为并发任务\n",
    "  - 获取事件循环对象\n",
    "    - 使用`asyncio.get_event_loop`函数\n",
    "  - 运行事件循环\n",
    "    - 使用事件循环对象的`run_until_complete`方法\n",
    "  - 关闭事件循环"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 10.5.5 利用异步编程处理网络并发\n",
    "\n",
    "- `socket`模块并不支持异步编程\n",
    "  - 网络套接字对象的输入/输出操作(`accept`、`send`、`recv`等方法)不能直接用于`await`语句\n",
    "- `asyncio`模块对`socket`进行了包装，提供了低级和高级两种类型的网络套接字操作方式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "#### 低级异步网络套接字编程\n",
    "\n",
    "- 通过事件循环对象的方法对已有的套接字对象进行操作，返回一个可 等待对象从而实现对异步编程的支持\n",
    "  - 已有的套接字对象必须设置为非 阻塞模式\n",
    "- 事件循环对象常用的套接字操作方法\n",
    "  - `sock_connect(sock, address)`：套接字对象`connect`方法的异步版本\n",
    "  - `sock_accept(sock)`：套接字对象`accept`方法的异步版本\n",
    "  - `sock_recv(sock, nbytes)`：套接字对象`recv`方法的异步版本\n",
    "  - `sock_recv_into(sock, buf)`：套接字对象`recv_into`方法的异步版本\n",
    "  - `sock_sendall(sock, data)`：套接字对象`sendall`方法的异步版本\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- eg_10-13\n",
    "\n",
    "```python\n",
    "from socket import socket, AF_INET, SOCK_STREAM\n",
    "from socket import SOL_SOCKET, SO_REUSEADDR\n",
    "from datetime import datetime\n",
    "import asyncio\n",
    "\n",
    "\n",
    "async def service_task(conn, addr, loop):\n",
    "    print(f'客户端{addr}连接成功，等待输入 ...')\n",
    "    while True:                                           # 通信循环\n",
    "        data_recv = (await loop.sock_recv(conn, 1024))    # 异步接收数据\n",
    "        data_recv = data_recv.decode('utf-8')\n",
    "        now = datetime.now().strftime(\"%H:%M:%S\")\n",
    "        print(f'{now} 接收到来自{addr}的数据：{data_recv}')\n",
    "        send_data = f'接收到长度为 {len(data_recv)} 的数据'\n",
    "        send_data = send_data.encode('utf-8')\n",
    "        await loop.sock_sendall(conn, send_data)          # 异步发送数据\n",
    "        if not data_recv:\n",
    "            conn.close()\n",
    "            break\n",
    "    print(f'客户端{addr}连接结束！')\n",
    "\n",
    "\n",
    "async def server_routine(server_socket, loop):\n",
    "    while True:\n",
    "        conn, addr = await loop.sock_accept(server_socket)  # 异步接受连接\n",
    "        loop.create_task(service_task(conn, addr, loop))\n",
    "\n",
    "\n",
    "def main():\n",
    "    server_socket = socket(AF_INET, SOCK_STREAM)        # 创建套接字\n",
    "    server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # 端口重用\n",
    "    server_socket.bind(('127.0.0.1', 9000))               # 绑定地址\n",
    "    server_socket.listen()\n",
    "    print('TCP服务器启动，监听之中... ...')\n",
    "    server_socket.setblocking(False)  # 设置为非阻塞套接字\n",
    "    loop = asyncio.get_event_loop()\n",
    "    routine = server_routine(server_socket, loop)\n",
    "    loop.run_until_complete(routine)\n",
    "    loop.close()\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "#### 高级异步网络套接字编程\n",
    "\n",
    "- 低级套接字操作方式\n",
    "  - 需要手动将客户端请求创建为任务并在事件循环中注册\n",
    "  - 处理可能发生的各种异常、缓冲区管理等一系复杂的底层操作\n",
    "  - 容易出错且运行效率低\n",
    "- 事件循环对象中允许直接创建服务器对象(`asyncio.Server`)\n",
    "  - 是一个能够异步处理客户端请求的可等待对象\n",
    "  - 接收到客户端连接请求之后，将读写操作包 装为具有异步通信功能的输入流(`asyncio.StreamReader`)对象和输出流(`asyncio. StreamWriter`)对象"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- eg_10-14\n",
    "\n",
    "```python\n",
    "import asyncio\n",
    "from asyncio import start_server\n",
    "from datetime import datetime\n",
    "\n",
    "async def service_task(reader, writer):\n",
    "    addr = writer.get_extra_info('peername')\n",
    "    print(f'客户端{addr}连接成功，等待输入 ...')\n",
    "    while True:\n",
    "        data_recv = await reader.read(1024)    # 异步接收数据\n",
    "        data_recv = data_recv.decode('utf-8')\n",
    "        now = datetime.now().strftime(\"%H:%M:%S\")\n",
    "        print(f'{now} 接收到来自{addr}的数据：{data_recv}')\n",
    "        send_data = f'接收到长度为 {len(data_recv)} 的数据'\n",
    "        writer.write(send_data.encode('utf-8'))\n",
    "        await writer.drain()                   # 等待缓冲区刷新\n",
    "        if data_recv == '':\n",
    "            break\n",
    "    writer.close()                             # 关闭输出流\n",
    "    print(f'客户端{addr}连接结束！')\n",
    "\n",
    "async def main():\n",
    "    server = await start_server(service_task,  # 创建服务器对象\n",
    "                                '127.0.0.1', 9000)\n",
    "    print(f'TCP服务器启动，监听之中... ...')\n",
    "    async with server:\n",
    "        await server.serve_forever()           # 运行服务器\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    asyncio.run(main())\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## 10.6 套接字服务器\n",
    "\n",
    "- Python 标准库中的socketserver模块实现了一系列套接字服务器类，对多种套接 字的通信过程进行了封装，能够非常容易地实现套接字服务器端\n",
    "\n",
    "### 10.6.1 `socketserver`模块简介\n",
    "\n",
    "- `socketserver`模块中的套接字服务器类\n",
    "\n",
    "<center>\n",
    "    <img src=\"./figures/fig10-7.png\" width=\"60%\"/>\n",
    "</center>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 套接字服务器类的实例化需要两个参数\n",
    "  - `server_address`：服务器套接字的绑定地址\n",
    "  - `RequestHandlerClass`：客户端请求处理器类\n",
    "- 套接字服务器常用的方法和属性\n",
    "  - `serve_forever`方法：启动套接字服务器\n",
    "  - `shutdown`方法：关闭套接字服务器\n",
    "  - `address_family`属性：套接字的协议地址簇\n",
    "  - `server_address`属性：套接字绑定地址\n",
    "  - `socket`属性：套接字对象\n",
    "  - `allow_reuse_address`属性：套接字对象是否允许端口重用，默认为`False`\n",
    "  - `socket_type`属性：套接字类型(`SOCK_STREAM`或`SOCK_DGRAM`)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "- 请求处理器\n",
    "  - `StreamRequestHandler`：处理 TCP 请求\n",
    "  - `DatagramRequestHandler`：处理 UDP 请求\n",
    "- 请求处理器的核心方法为`handle`\n",
    "  - 实际应用中需继承请求处理器类，重写`handle`方法\n",
    "  - `handle`方法中可以通过 如下属性获取服务器和客户端的信息\n",
    "    - `self.request`：客户端请求的通信套接字对象(在 TCP 和 UDP 中有所差异)\n",
    "    - `self.client_address`：客户端地址\n",
    "    - `self.server`：套接字服务器对象"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "### 10.6.2 利用套接字服务器处理网络并发\n",
    "\n",
    "- eg_10-15\n",
    "\n",
    "```python\n",
    "from socketserver import ThreadingTCPServer, StreamRequestHandler\n",
    "from datetime import datetime\n",
    "\n",
    "class TCPHandler(StreamRequestHandler):                     # 请求处理器\n",
    "    def handle(self):\n",
    "        print(f'客户端{self.client_address}连接成功，等待输入 ...')\n",
    "        while True:                                         # 通信循环\n",
    "            data_recv = self.request.recv(1024)             # 接收数据\n",
    "            data_recv = data_recv.decode('utf-8')\n",
    "            now = datetime.now().strftime(\"%H:%M:%S\")\n",
    "            print(f'{now} 接收到来自{self.client_address}的数据：{data_recv}')\n",
    "            send_data = f'接收到长度为 {len(data_recv)} 的数据'\n",
    "            self.request.send(send_data.encode('utf-8'))    # 发送数据\n",
    "            if not data_recv:\n",
    "                break\n",
    "        print(f'客户端{self.client_address}连接结束！')\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    with ThreadingTCPServer(('127.0.0.1', 9000), TCPHandler) as server:\n",
    "        print('TCP服务器启动，监听之中... ...')\n",
    "        server.serve_forever()\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "author": "liuchen",
  "celltoolbar": "幻灯片",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  },
  "rise": {
   "enable_chalkboard": true,
   "footer": "",
   "progress": true,
   "scroll": true,
   "slideNumber": true
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "url": "https://github.com/hitlic/python_book"
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
